<!--
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2022-12-02 17:04:52
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-06-15 15:42:07
 * @FilePath: \cxl-h5\src\components\Tab.vue
-->
<template>
    <section class="tab-container">
        <ul>
            <li
                :style="{ width: 100 / list.length + '%' }"
                :class="[index == defaultIndex ? 'active' : '']"
                v-for="(item, index) in list"
                :key="item"
                @click="onTouch(index)"
            >
                {{ item }}
            </li>
        </ul>
    </section>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect } from 'vue'
//接收父级传递的参数
const props = defineProps(['list', 'selectIndex'])
//注册父级回调
const emits = defineEmits(['change'])
//定义默认的下标
const defaultIndex = ref(0)
//定义tab数组
const list: any[] = reactive([])
//监听父级参数首次的变化
watchEffect(() => {
    list.length = 0
    if (props.list) {
        list.push(...props.list)
    }
    defaultIndex.value = props.selectIndex === undefined ? 0 : props.selectIndex
})
//监听点击事件，并向父级传递所选择的下标
const onTouch = (index: number) => {
    if (defaultIndex.value !== index) {
        defaultIndex.value = index
        emits('change', index)
    }
}
</script>

<style scoped lang="scss">
.tab-container {
    background-color: var(--cxl-color-f2f6f8);
    padding-bottom: var(--cxl-size-10);
    ul {
        display: flex;
        box-sizing: border-box;
        line-height: var(--cxl-size-40);
        background-color: var(--cxl-color-white);

        li {
            text-align: center;
            position: relative;
            transition: all 0.35s;
            color: var(--cxl-color-666666);
            font-size: var(--cxl-size-15);
            &::after {
                content: '';
                width: 2rem;
                height: 3px;
                background-color: var(--cxl-color-white);
                display: block;
                position: absolute;
                left: calc(50% - 1rem);
                bottom: 0;
                border-radius: 2px;
                transition: all 0.35s;
            }
            &.active {
                color: var(--cxl-color-primary);
                &::after {
                    background-color: var(--cxl-color-primary);
                }
            }
        }
    }
}
</style>
